<template>
  <div>
    <el-tabs size="mini" v-model="activeName" type="card" :before-leave='leaveTab' @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="0">
        <el-form class="form-container" :model="form" :rules="rules" ref="postForm" label-width="200px"
          v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="供应商编号：" prop="code">
                <el-input size="mini" v-model="form.code" disabled />
              </el-form-item>
              <el-form-item label="推荐人：" prop="pname">
                <!-- <el-input size="mini" v-model="form.pname" placeholder="请输入推荐人" :disabled="is_view"  /> -->
                <el-select v-model="form.partnerId" size="mini" filterable remote reserve-keyword placeholder="请输入推荐人"
                  :remote-method="getMemberList" :loading="loading">
                  <el-option v-for="item in memberIdList" :key="item.id" :label="item.contactPhone + '|' + item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="提成比例：" prop="partnerRate">
                <el-input size="mini" v-model="form.partnerRate" placeholder="请输入推荐人提成比例" class="w60"
                  :disabled="is_view" />%
              </el-form-item>
              <el-form-item label="供应商名称：" prop="name">
                <el-input size="mini" v-model="form.name" placeholder="请输入供应商名称" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="联系人：" prop="consignee">
                <el-input size="mini" v-model="form.consignee" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="联系电话：" prop="contactPhone">
                <el-input size="mini" v-model="form.contactPhone" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="联系邮箱：" prop="contactEmail">
                <el-input size="mini" v-model="form.contactEmail" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="所在地区：" prop="contactArea">
                <area-select v-model="form.contactArea" />
              </el-form-item>
              <el-form-item label="详细地址：" prop="contactAddress">
                <el-input size="mini" v-model="form.contactAddress" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item v-if="!is_view">
                <el-button type="primary" size="mini" @click="next()" :loading="saveLoading">下一步</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="工商信息" name="1">
        <el-form class="form-container" :model="form" :rules="rules2" ref="postForm2" label-width="200px"
          v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="统一社会信用代码：" prop="idNumber">
                <el-input size="mini" v-model="form.idNumber" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="企业名称：" prop="company">
                <el-input size="mini" v-model="form.company" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="注册地址：" prop="address">
                <el-input size="mini" v-model="form.address" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="法定代表人：" prop="legalPerson">
                <el-input size="mini" v-model="form.legalPerson" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="注册资本：" prop="registerCapital">
                <el-input size="mini" v-model="form.registerCapital" placeholder="" :disabled="is_view" class="w60" />
                万元
              </el-form-item>
              <el-form-item label="成立日期：" prop="contactArea">
                <el-date-picker size="mini" format="yyyy年MM月dd日" value-format="yyyy-MM-dd" v-model="form.regDate"
                  type="date" placeholder="">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="经营范围：" prop="scope">
                <common-input type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" placeholder=""
                  v-model="form.scope" />
              </el-form-item>
              <el-form-item label="营业执照：" prop="picture">
                <pic-sel :maxNum="5" style="float:left" v-model="form.picture" />
              </el-form-item>
              <el-form-item label="法人身份证：" prop="idPicture">
                <pic-sel :maxNum="2" style="float:left" v-model="form.idPicture" />
              </el-form-item>
              <el-form-item v-if="!is_view">
                <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                <el-button type="primary" size="mini" @click="next()">下一步</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="签约信息" name="2">
        <el-form class="form-container" :model="form" :rules="rules3" ref="postForm3" label-width="200px"
          v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="签约类目：">
                <el-button v-if="!is_view" @click="handleSelect" type="primary" icon="el-icon-plus"
                  size="mini">添加签约类目</el-button>
                <table class="ikd-input-table" style="width: 100%;margin-top: 6px;" cellspacing="1" cellpadding="8">
                  <thead>
                    <th nowrap>序号</th>
                    <th nowrap>类目</th>
                    <th nowrap v-if="!is_view">操作</th>
                  </thead>
                  <tbody>
                    <template v-for="(item, idx) in categoryList">
                      <tr :key="item.id" v-if="item">
                        <td>{{ idx + 1 }}</td>
                        <td>{{ item.fullName }}</td>
                        <td v-if="!is_view">
                          <el-button type="text" @click="delete_item(idx)">删除</el-button>
                        </td>
                      </tr>
                    </template>
                  </tbody>
                </table>
              </el-form-item>
              <el-form-item label="签约有效期：" prop="contractStart">
                <el-date-picker size="mini" format="yyyy年MM月dd日" value-format="yyyy-MM-dd" v-model="form.contractStart"
                  type="date" placeholder="">
                </el-date-picker>
                <span style="margin:0 10px;">到</span>
                <el-date-picker size="mini" format="yyyy年MM月dd日" value-format="yyyy-MM-dd" v-model="form.contractEnd"
                  type="date" placeholder="">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="签约合同（纸质）：">
              </el-form-item>
              <el-form-item v-if="!is_view">
                <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                <el-button type="primary" size="mini" @click="next()">下一步</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-tab-pane>
      <el-tab-pane label="财务信息" name="3">
        <el-form class="form-container" :model="form" :rules="rules4" ref="postForm4" label-width="200px"
          v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="开户行：" prop="bank">
                <el-input size="mini" v-model="form.bank" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="开户名：" prop="bankHost">
                <el-input size="mini" v-model="form.bankHost" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="银行卡账号：" prop="bankAccount">
                <el-input size="mini" v-model="form.bankAccount" placeholder="" :disabled="is_view" />
              </el-form-item>
              <el-form-item label="关闭提现：" prop="closeWithdraw">
                <el-radio-group :disabled="is_view" v-model="form.closeWithdraw">
                  <el-radio :label="0">正常</el-radio>
                  <el-radio :label="1">关闭</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="查看商家：" prop="viewSeller">
                <el-radio-group :disabled="is_view" v-model="form.viewSeller">
                  <el-radio :label="1">允许</el-radio>
                  <el-radio :label="0">不允许</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="!is_view">
                <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                <el-button type="primary" size="mini" @click="next()">完成</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="选择类目" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="500px">
      <el-form :model="form" :rules="rules" ref="categoryForm" label-width="150px">
        <el-form-item label="选择类目" prop="categoryIds">
          <el-cascader placeholder="请选择分类" v-model="categoryForm.categoryIds" size="mini" :options="tree_list"
            :props="props">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="okSelect()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'推荐人选择'" :visible.sync="dialogFormVisibles" width="500px" @close="dialogClose">

      <div slot="footer" class="dialog-footer">11111111
        <!-- <el-button size="mini" @click="cancel('form')">取消</el-button>
          <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
          <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  industry_category_tree,
  industry_category_detail
} from '../../api/industry';
import {
  agency_save,
  agency_detail
} from '../../api/agency';
import {
  agency_list,
} from '../../api/partner';
// import {
//     age_list
// } from '../../utils/utils';
// import {
//     org_school_tree
// } from '../../api/org/index';
import {
  isInteger
} from '../../utils/validator'
import {
  next_no
} from '../../api/sys';

export default {
  name: 'agency-create',
  components: {
    'area-select': () => import('../../components/AreaSelect/index'),
    'pic-sel': () => import('../../components/PicSel/index')
  },
  props: {
    formData: Object
  },
  watch: {
    formData: {
      immediate: true,
      handler(val) {
        this.currentId = val.agency_id;
        this.$nextTick(() => {
          this.$refs.postForm.resetFields();
          this.$refs.postForm2.resetFields();
          this.$refs.postForm3.resetFields();
          this.$refs.postForm4.resetFields();
        });

        if (this.currentId > 0) {
          this.is_view = val.is_view;
          this.getDetail()
          console.log('111111111111111111111')
          this.getMemberList()
        } else {
          this.resetTemp();
        }
      }
    }
  },
  data() {
    return {
      props: { value: 'id', label: 'name', checkStrictly: true },
      categoryForm: {
        categoryIds: []
      },
      can_edit: true,
      dialogFormVisibles: false,
      memberIdList: [],
      form: {
        id: 0,
        name: undefined,
        partnerId: undefined,
        code: undefined,
        consignee: undefined,
        contactPhone: undefined,
        contactEmail: undefined,
        contactArea: undefined,
        contactAddress: undefined,
        idNumber: undefined,
        company: undefined,
        address: undefined,
        legalPerson: undefined,
        registerCapital: undefined,
        regDate: undefined,
        scope: undefined,
        picture: undefined,
        idPicture: undefined,
        bank: undefined,
        bankHost: undefined,
        bankAccount: undefined,
        categoryIds: [],
        closeWithdraw: 0,
        viewSeller: 1,
        partnerRate: 10
      },
      currentId: 0,
      formStatus: 'create',
      rules: {
        name: [
          {
            required: true,
            message: '请输入供应商名称',
            trigger: 'blur'
          }
        ],
        consignee: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }
        ],
        contactPhone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          }
        ],
        contactArea: [
          {
            required: true,
            message: '请选择所在地区',
            trigger: 'blur'
          }
        ],
        contactAddress: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }
        ],
      },
      rules2: {
        idNumber: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ],
        company: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        legalPerson: [
          {
            required: true,
            message: '请输入法定代表人',
            trigger: 'blur'
          }
        ],
        registerCapital: [
          {
            validator: isInteger,
            trigger: 'blur'
          }
        ],
        regDate: [
          {
            required: true,
            message: '请选择成立日期',
            trigger: 'blur'
          }
        ],
        picture: [
          {
            required: true,
            message: '请选择营业执照',
            trigger: 'blur'
          }
        ],
        idPicture: [
          {
            required: true,
            message: '请选择法人身份证',
            trigger: 'blur'
          }
        ],
      },
      rules3: {
        idNumber: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ],
        company: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        legalPerson: [
          {
            required: true,
            message: '请输入法定代表人',
            trigger: 'blur'
          }
        ],
        registerCapital: [
          {
            required: true,
            message: '请输入注册资本',
            trigger: 'blur'
          }
        ],
        regDate: [
          {
            required: true,
            message: '请选择成立日期',
            trigger: 'blur'
          }
        ],
        picture: [
          {
            required: true,
            message: '请选择营业执照',
            trigger: 'blur'
          }
        ],
        idPicture: [
          {
            required: true,
            message: '请选择法人身份证',
            trigger: 'blur'
          }
        ],
      },
      rules4: {
      },
      loading: false,
      fetchSuccess: true,
      saveLoading: false,
      is_view: false,
      activeName: "0",
      prevActiveName: "0",
      tree_list: [],
      dialogFormVisible: false,
      categoryList: []
    }
  },
  created() {
    this.getTree();

  },
  methods: {
    // 搜索指定合伙人id
    getMemberList(e) {
      console.log(e)
      // if (e) {
      let data = {
        keyword: e
      }
      agency_list(data).then(res => {
        console.log(res, '3333333333333333333333333')
        this.memberIdList = res.data.list
      })
      // }

    },
    handleClickOpenPartner() {
      console.log("1111111111")
      this.dialogFormVisibles = true;
    },
    dialogClose() {
      this.dialogFormVisibles = false;
    },
    getTree() {
      industry_category_tree(0).then((res) => {
        this.tree_list = res.data;
      }).catch((err) => {
        this.tree_list = []
      });
    },
    resetTemp() {
      this.form = {
        id: 0,
        name: undefined,
        code: undefined,
        consignee: undefined,
        contactPhone: undefined,
        contactEmail: undefined,
        contactArea: undefined,
        contactAddress: undefined,
        idNumber: undefined,
        company: undefined,
        address: undefined,
        legalPerson: undefined,
        registerCapital: undefined,
        regDate: undefined,
        scope: undefined,
        picture: undefined,
        idPicture: undefined,
        bank: undefined,
        bankHost: undefined,
        bankAccount: undefined,
        categoryIds: [],
        closeWithdraw: 0,
        viewSeller: 1,
        partnerRate: 10,
        partnerId: undefined
      };
      next_no(3).then(response => {
        this.form.code = response.data.number;
      });
      this.can_edit = true;
    },
    leaveTab(activeName, oldActiveName) {
      if (this.form.id > 0) {
        return true;
      }
      if (this.prevActiveName == this.activeName) {
        return false;
      }

      this.prevActiveName = this.activeName
      return true;
    },
    getDetail() {
      agency_detail(this.currentId).then(response => {
        this.form = response.data;
        let area = [];
        if (this.form.provinceCode) {
          area.push(this.form.provinceCode);
          if (this.form.cityCode) {
            area.push(this.form.cityCode);
            if (this.form.countyCode) {
              area.push(this.form.countyCode);
            }
          }
        }
        this.form.contactArea = area.join(",");
        this.categoryList = this.form.categoryList;
        if (!this.categoryList) {
          this.categoryList = []
        }
        this.formStatus = "update";
        this.can_edit = true
      }).catch(() => {
        this.formStatus = ""
      });
    },
    cancel() {
      this.$emit('cancelCreate');
    },
    next() {
      let form = "";
      if (this.activeName == "0") {
        form = "postForm";
      } else if (this.activeName == "1") {
        form = "postForm2";
      } else if (this.activeName == "2") {
        form = "postForm3";
      } else if (this.activeName == "3") {
        form = "postForm4";
      }

      if (form) {
        this.$refs[form].validate(valid => {
          if (valid) {
            if (this.activeName == "3") {
              //最后一步
              this.form.provinceCode = 0;
              this.form.cityCode = 0;
              this.form.countyCode = 0;
              if (this.form.contactArea) {
                let aa = this.form.contactArea.split(",");
                this.form.provinceCode = aa[0] || 0;
                this.form.cityCode = aa[1] || 0;
                this.form.countyCode = aa[2] || 0
              }

              this.form.categoryIds = [];
              if (this.categoryList && this.categoryList.length > 0) {
                this.categoryList.forEach((item) => {
                  this.form.categoryIds.push(item.id);
                })
              }

              this.saveLoading = true;
              agency_save(this.form)
                .then(() => {
                  this.saveLoading = false;
                  this.$message.success(this.form.id > 0 ? "供应商信息已保存" : "成功添加供应商");
                  this.$emit('okCreate');
                }).catch((err) => {
                  this.saveLoading = false;
                })
            } else {
              this.prevActiveName = this.activeName
              this.activeName = "" + (parseInt(this.activeName) + 1) + "";
            }
          }
        });
      }
    },
    prev() {
      this.prevActiveName = this.activeName
      this.activeName = "" + (parseInt(this.activeName) - 1) + "";
    },
    handleClick(tab, event) {
      // this.prevActiveName = this.activeName
      // console.log(this.prevActiveName + "-" + this.activeName)
    },
    handleSelect() {
      this.dialogFormVisible = true;
    },
    okSelect() {
      if (this.categoryForm.categoryIds && this.categoryForm.categoryIds.length > 0) {
        let id = this.categoryForm.categoryIds[this.categoryForm.categoryIds.length - 1];

        industry_category_detail(id).then((res) => {
          if (res.data) {
            let has = false;
            this.categoryList.forEach((item) => {
              if (item.id == res.data.id) {
                has = true;
                return false;
              }
            });

            if (!has) {
              this.categoryList.push(res.data)
            }
            this.dialogFormVisible = false;
          }
        }).catch((err) => {

        })
      } else {

      }
      // console.log(this.categoryForm.categoryIds)
    },
    delete_item(idx) {
      this.$confirm('确定删除这个类目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let items = [];

          this.categoryList.forEach((item, item_idx) => {
            if (item_idx != idx) {
              items.push(item);
            }
          })

          this.categoryList = items;
        }).catch(() => { });
    }
  }
}
</script>
